//导入数据库操作模块
const db = require('../db/index');

// 
const fs = require('fs');
const path = require('path');

const iconv = require('iconv-lite');

exports.addImages = (req, res) => {
    console.log(req.body)
    console.log('----------')
    console.log(req.file)

    const articleInfo = req.file

    articleInfo.url = 'http://127.0.0.1:3007/uploads/' + articleInfo.filename
    articleInfo.name = iconv.decode(Buffer.from(articleInfo.originalname, 'binary'), 'utf-8');
    console.log(articleInfo.url,"合并地址")
    const sqlStr = 'INSERT INTO images (url, name, filename) VALUES (?, ?, ?)'
    db.query(sqlStr, [articleInfo.url, articleInfo.name, articleInfo.filename], (err, results) => {
                // 判断sql语句是否执行成功
        if (err) {
            console.log(err)
            return res.cc(err)
                } 
                // 判断影响行数是否为1
                if (results.affectedRows !== 1) res.send({ status: 1, message: "添加失败请稍后再试" })
                // 注册用户成功
                // res.send({status:0,message:"添加成功！"})
        console.log(results, "添加图片")
        console.log('添加成功')
            res.send({
                "errno": 0, // 注意：值是数字，不能是字符串
                "data": {
                    "url": articleInfo.url, // 图片 src ，必须
                    "alt": "yyy", // 图片描述文字，非必须
                    "href": "zzz", // 图片的链接，非必须
                    'id': results.insertId,
                    'filename': articleInfo.filename
                }
            })

    })



}

exports.getImages = (req, res) => {
    const sqlStr = 'SELECT * FROM images'
    db.query(sqlStr, (err, results) => {
        res.send(results)
        console.log(results)
    })
}

exports.deleteImages = (req, res) => {
    const id = parseInt(req.query.id)
    const filename = req.query.filename
    console.log(id, filename)

    const sqlStr = 'DELETE FROM images WHERE id=?'
    db.query(sqlStr, [id], (err, results) => {
        if (err) {
            console.log(err)
            return res.cc(err)
        }
        if (results.affectedRows !== 1) return res.send({ status: 1, message: "删除失败" })
        if (results.affectedRows === 1) {
            console.log(filename)
            fs.unlink(path.join(__dirname, '../', '/uploads/', filename), (err) => {
                if (err) {
                  console.error('Error deleting file:', err);
                } else {
                  console.log('File deleted successfully');
                }
              });
            // console.log(path.join(__dirname, '../', '/uploads/', filename))
            res.send({
                status: 0,
                message: '删除成功'
            })
        }
    })
}